// NodePathUtil.ts
import { Node, Scene } from 'cc';

export class NodePathUtil {
    /**
     * 从根路径查找节点，路径格式如：'/Canvas/Main/Node'
     */
    static findByRootPath(root: Node | Scene, path: string): Node | null {
        if (!path.startsWith('/')) return null;
        const parts = path.split('/').filter(Boolean);

        // Scene 是 Node 的子类，所以可以统一处理为 Node
        let current: Node | null = root as Node;

        for (let i = 0; i < parts.length; i++) {
            const name = parts[i];
            let found = false;

            for (let j = 0; j < current.children.length; j++) {
                const child = current.children[j];
                if (child.name === name) {
                    current = child;
                    found = true;
                    break;
                }
            }

            if (!found) return null;
        }

        return current;
    }

    /**
     * 获取从场景根节点开始的完整路径，例如 '/Canvas/Main/Node'
     */
    static getPath(node: Node): string {
        const stack: string[] = [];

        while (node) {
            stack.push(node.name);
            node = node.parent!;
        }

        return '/' + stack.reverse().join('/');
    }

    /**
     * 从指定节点出发，根据相对路径查找节点，例如 '../../Group'
     */
    static findByRelativePath(
        startNode: Node,
        relativePath: string,
    ): Node | null {
        const parts = relativePath
            .split('/')
            .filter((part) => part.length > 0);
        let current: Node | null = startNode;

        for (let i = 0; i < parts.length; i++) {
            const part = parts[i];
            if (part === '..') {
                current = current.parent;
                if (!current) return null;
            } else {
                let found = false;
                for (let j = 0; j < current.children.length; j++) {
                    const child = current.children[j];
                    if (child.name === part) {
                        current = child;
                        found = true;
                        break;
                    }
                }
                if (!found) return null;
            }
        }

        return current;
    }
}
